package com.jyu.hakkatranslation.controller;

import com.jyu.hakkatranslation.Exception.Enums.LoginEnum;
import com.jyu.hakkatranslation.pojo.User;
import com.jyu.hakkatranslation.service.UserService;
import com.jyu.hakkatranslation.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    UserService userService;


    /**
     * 注册操作
     * @param session
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String Register(HttpSession session,@RequestBody User user){
        String password = user.getPassword();
        String passwordEnsure = user.getPasswordEnsure();
        if(passwordEnsure.equals("")||passwordEnsure!= password){
            session.setAttribute("msg",LoginEnum.REGISTER_ANSWER_INCONSISTENT);
            return "register";
        }

        boolean registerState = userService.register(user);
        if(registerState){//如果注册失败
            session.setAttribute("msg",LoginEnum.LOGIN_SUCCESS);
            return "login";
        }else{
            session.setAttribute("msg",LoginEnum.REGISTER_ERROR);
            return "register";
        }
    }

    /**
     * 登录操作
     * @param session
     * @param uservo
     * @return
     */
    @GetMapping("/login")
    public String login(HttpSession session, @RequestBody UserVo uservo){
        String username = uservo.getUsername();
        String password = uservo.getPassword();
        boolean loginState = userService.login(username, password);
        if(!loginState){
            session.setAttribute("msg",LoginEnum.USER_NO_EXIST);
            return "login";
        }else{
            session.setAttribute("user",uservo);
            return "login";
        }


//        String sessionCode = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//        System.out.println(" session中获取的验证码:  " + sessionCode);
//        if (code.equalsIgnoreCase(sessionCode)){
//            System.out.println("正确");
//            return "验证码相同,验证通过";
//        }else {
//            System.out.println("错误");
//            return "验证码不同,验证失败";
//        }
    }

}
